package com.ultrapower.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ultrapower.commons.base.BaseController;
import com.ultrapower.commons.result.PageInfo;
import com.ultrapower.commons.scan.Traced;
import com.ultrapower.commons.shiro.ShiroUser;
import com.ultrapower.commons.utils.JsonUtils;
import com.ultrapower.commons.utils.StringUtils;
import com.ultrapower.model.Enterprise;
import com.ultrapower.model.Orderlist;
import com.ultrapower.model.Organization;
import com.ultrapower.model.Product;
import com.ultrapower.model.Task;
import com.ultrapower.model.User;
import com.ultrapower.service.IOrderService;
import com.ultrapower.service.IOrganizationService;
import com.ultrapower.service.IProductService;
import com.ultrapower.service.ITaskService;
import com.ultrapower.service.IUserService;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sz
 * @since 2018-07-31
 */
@Controller
@RequestMapping("/task")
public class TaskController extends BaseController {

    @Autowired private ITaskService taskService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrganizationService orgService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IUserService userService;
    
    @GetMapping("/manager")
    public String manager() {
        return "admin/task/taskList";
    }
    
    @GetMapping("/product")
    public String product() {
        return "admin/task/product";
    }
    
    @GetMapping("/enterprise")
    public String enterprise() {
        return "admin/task/enterpriselist";
    }
    
    @PostMapping("/dataGrid")
    @ResponseBody
    public PageInfo dataGrid(String companyName,String type,Integer page, Integer limit, String sort, String order) {
    	sort = "id";
    	order = "asc";
        PageInfo pageInfo = new PageInfo(page, limit, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();
        ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        if(!shiroUser.getRoles().contains("admin")&&shiroUser.getRoles().contains("cm")) {
        	condition.put("creater", getUserId());       	
        }
        if (StringUtils.isNotBlank(companyName)) {
            condition.put("companyName", companyName);
        }
        if (StringUtils.isNotBlank(type)) {
            condition.put("type", type);
        }
        pageInfo.setCondition(condition);
        taskService.selectDataGrid(pageInfo);
        return pageInfo;
    }
    
    @PostMapping("/enterpriseGrid")
    @ResponseBody
    public PageInfo enterpriseGrid(Enterprise enterprise, String primaryP,String hotP,Integer page, Integer limit, String sort, String order, String cityName,String industry,String companyName,String develop,String type,String scale) {
    	sort = "id";
    	order = "asc";
        PageInfo pageInfo = new PageInfo(page, limit, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();
        String province = enterprise.getProvince();
        User user = userService.selectById(getUserId());
    	Organization oi = orgService.selectById(user.getOrganizationId());
    	if(StringUtils.isNotBlank(oi.getProvince())){
    		if(StringUtils.isNotBlank(province)){
    			if(province.equals(oi.getProvince())){
    				condition.put("province", oi.getProvince());
    			}else{
    				return pageInfo;
    			}
    		}else{
    			condition.put("province", oi.getProvince());
    		}
    	}
    
    		if(StringUtils.isNotBlank(cityName)){
    				condition.put("cityName", cityName);    		
    		}else{
    			condition.put("cityName", oi.getCity());
    		}
    	

        if (StringUtils.isNotBlank(primaryP)) {
            condition.put("primaryP", primaryP);
        }
        if (StringUtils.isNotBlank(hotP)) {
            condition.put("hotP", hotP);
        }
        if (StringUtils.isNotBlank(industry)) {
            condition.put("industry", industry);
        }
        if (StringUtils.isNotBlank(develop) && !"0".equals(develop)) {
            condition.put("develop", develop);
        }
        if (StringUtils.isNotBlank(companyName)) {
            condition.put("companyName", companyName);
        }
        if (StringUtils.isNotBlank(industry)) {
            condition.put("industry", industry);
        }
        if (StringUtils.isNotBlank(type)) {
            condition.put("type", type);
        }
        if (StringUtils.isNotBlank(scale)) {
            condition.put("scale", scale);
        }
        pageInfo.setCondition(condition);
        taskService.selectTaskEnterprise(pageInfo);
        return pageInfo;
    }
    
    /**
     * 添加页面
     * @return
     */
    @GetMapping("/addPage")
    public String addPage() {
        return "admin/task/taskAdd";
    }
    
    /**
     * 添加页面
     * @return
     */
    @GetMapping("/addPageBatch")
    public String addPageBatch(Model model) {
    	Organization org = orgService.selectOrgByUserId(getUserId());
    	if(org.getCity()!=null&&org.getCity()!="")
    	model.addAttribute("city", org.getCity());
        return "admin/task/taskAddbatch";
    }
    
    /**
     * 添加
     * @param 
     * @return
     */
    @Traced(name="添加任务")
    @PostMapping("/addBatch")
    @ResponseBody
    public Object addBatch(Enterprise enterprise, String primaryP,String hotP,String enterpriseIds,String name,String describe,String area,String orgId,String isAll) {
    	System.out.println(enterprise.getCityName());
    	List<Task> tasks = new ArrayList<Task>();
    	Orderlist order = new Orderlist();
		order.setName(name);
		order.setDescribe(describe);
		order.setCreateTime(new Date());
		order.setUpdateTime(new Date());
		order.setDeleteFlag(0);
		if(enterprise.getCityName()!=null&&enterprise.getCityName()!=""){
			order.setCity(enterprise.getCityName());
		}else {
			Organization org = orgService.selectOrgByUserId(getUserId());
			order.setCity(org.getCity());
		}
		order.setCountry(area);
		order.setCreater(getUserId());
		if(orgId!=null&&!"".equals(orgId)) {
			order.setUserId(userService.selectcmByorgId(orgId));
		}else {
			order.setUserId(getUserId());
		}
		boolean b=orderService.insert(order);
		List<Integer> enterpriseList = new ArrayList<>();
		if(isAll!=null&&isAll.equals("true")) {
			 Map<String, Object> condition = new HashMap<String, Object>();
		        String province = enterprise.getProvince();
		        User user = userService.selectById(getUserId());
		    	Organization oi = orgService.selectById(user.getOrganizationId());
		    			    
		    	condition.put("province", oi.getProvince());
		    		
		    	if(StringUtils.isNotBlank(oi.getCity())){
		    		
		    			condition.put("cityName", oi.getCity());
		    		
		    	}else {
		    		condition.put("cityName", enterprise.getCityName());
		    	}
		    			
		        if (StringUtils.isNotBlank(primaryP)) {
		            condition.put("primaryP", primaryP);
		        }
		        if (StringUtils.isNotBlank(hotP)) {
		            condition.put("hotP", hotP);
		        }
		        if (StringUtils.isNotBlank(enterprise.getIndustry())) {
		            condition.put("industry", enterprise.getIndustry());
		        }
		        if (StringUtils.isNotBlank(enterprise.getDevelop()) && !"0".equals(enterprise.getDevelop())) {
		            condition.put("develop", enterprise.getDevelop());
		        }
		        if (StringUtils.isNotBlank(enterprise.getCompanyName())) {
		            condition.put("companyName", enterprise.getCompanyName());
		        }
		        if (StringUtils.isNotBlank(enterprise.getType())) {
		            condition.put("type", enterprise.getType());
		        }
		        if (StringUtils.isNotBlank(enterprise.getScale())) {
		            condition.put("scale", enterprise.getScale());
		        }
		        enterpriseList = taskService.selectTaskEnterpriseId(condition);
		}else {
		   		enterpriseList = JsonUtils.parse(enterpriseIds, List.class);
		}
		if(b) {
	    	for(int enterpriseId:enterpriseList) {
	    	Task task = new Task();
	    	task.setOrderId(order.getId());
	        task.setCreateTime(new Date());
	        task.setUpdateTime(new Date());
	        task.setDeleteFlag(0);
	        task.setPrimaryProduct(Integer.parseInt(primaryP));
	        task.setHotProduct(Integer.parseInt(hotP));
	        task.setEnterpriseId(enterpriseId);
	        task.setCreater(Long.parseLong(getUserId().toString()));
	        task.setType(1);
	        tasks.add(task);
	    	}
    	b=b&(taskService.insertBatch(tasks, tasks.size()));
		}
         if (b) {
             return renderSuccess("添加成功！");
         } else {
             return renderError("添加失败！");
         }
    }
    
    /**
     * 框选商圈后动态添加任务
     * @param 
     * @return
     */
    @Traced(name="框选商圈后动态添加任务")
    @PostMapping("/addBatchTask")
    @ResponseBody
    public Object addBatchTask(String primaryP,@RequestParam(value = "ids[]") String[] ids) {
    	ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
    	Long createrId = user.getId();
    	Organization org = orgService.selectOrgByUserId(createrId);
    	//这里判断，如果是否之前已经存在该企业推广该产品，如果已经存在则不添加
		Orderlist order = new Orderlist();
		order.setName("商圈信息");
		//order.setUserId(Integer.parseInt(userId));
		order.setCreateTime(new Date());
		order.setUpdateTime(new Date());
		order.setDeleteFlag(0);
		order.setCity(org.getCity());
		order.setCountry(org.getArea());
		order.setDeleteFlag(0);
		order.setCreater(createrId);
		orderService.insert(order);
		for (int i = 0; i < ids.length; i++) {
			boolean flag = taskService.isExistence(Integer.parseInt(ids[i]),Integer.parseInt(primaryP));
			if(!flag){
				Task task = new Task();
				task.setOrderId(order.getId());
				task.setCreateTime(new Date());
				task.setUpdateTime(new Date());
				task.setDeleteFlag(0);
				List<Product> listProduct = productService.selectTreeGrid();
				Random random = new Random();
				int n = random.nextInt(listProduct.size());
				Product product = listProduct.get(n);
				task.setPrimaryProduct(Integer.parseInt(primaryP));
				task.setHotProduct(product.getId());
				task.setEnterpriseId(Integer.parseInt(ids[i]));
				task.setCreater(createrId);
				task.setType(1);
				task.setDeleteFlag(0);
				taskService.insert(task);
			}
		}
		return renderSuccess();
    }
    
    /**
     * 添加
     * @param 
     * @return
     */
    @Traced(name="添加任务")
    @PostMapping("/add")
    @ResponseBody
    public Object add(@Valid Task task) {
        task.setCreateTime(new Date());
        task.setUpdateTime(new Date());
        task.setDeleteFlag(0);
        boolean b = taskService.insert(task);
        if (b) {
            return renderSuccess("添加成功！");
        } else {
            return renderError("添加失败！");
        }
    }
    
    /**
     * 删除
     * @param id
     * @return
     */
    @Traced(name="删除任务")
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(int id) {
        boolean b = taskService.deleteById(id);
        if (b) {
            return renderSuccess("删除成功！");
        } else {
            return renderError("删除失败！");
        }
    }
    
    /**
     * 编辑
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/editPage")
    public String editPage(Model model, Long id) {
        Task task = taskService.selectById(id);
        model.addAttribute("task", task);
        return "admin/task/taskEdit";
    }
    
    /**
     * 编辑
     * @param 
     * @return
     */
    @Traced(name="编辑任务")
    @PostMapping("/edit")
    @ResponseBody
    public Object edit(@Valid Task task) {
        task.setUpdateTime(new Date());
        boolean b = taskService.updateById(task);
        if (b) {
            return renderSuccess("编辑成功！");
        } else {
            return renderError("编辑失败！");
        }
    }
}
